package com.gitee.ixtf.lucene.kotlinx

import com.gitee.ixtf.core.PageQueryResult
import com.gitee.ixtf.lucene.Jlucene.ID
import org.apache.lucene.search.*

fun Query.count(searcher: IndexSearcher): Int {
  val totalHitCountCollector = TotalHitCountCollector()
  searcher.search(this, totalHitCountCollector)
  return totalHitCountCollector.totalHits
}

fun Query.ids(
    searcher: IndexSearcher,
    first: Int,
    pageSize: Int,
    sort: Sort? = null
): Collection<String> {
  val topDocs =
      if (sort == null) searcher.search(this, first + pageSize)
      else searcher.search(this, first + pageSize, sort)
  val storedFields = searcher.storedFields()
  return topDocs.scoreDocs.drop(first).map { storedFields.document(it.doc).get(ID) }
}

fun Query.result(
    searcher: IndexSearcher,
    first: Int,
    pageSize: Int,
    sort: Sort? = null
): PageQueryResult<String> {
  val count = count(searcher).toLong()
  return if (count < 1)
      PageQueryResult(first = first, pageSize = pageSize, count = count, data = listOf())
  else
      PageQueryResult(
          first = first,
          pageSize = pageSize,
          count = count,
          data = ids(searcher, first, pageSize, sort))
}

fun BooleanQuery.Builder.result(
    searcher: IndexSearcher,
    first: Int,
    pageSize: Int,
    sort: Sort? = null
) = build().result(searcher, first, pageSize, sort)
